<?php

namespace app\components\oss\qiniu;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use yii\base\Component;

/**
 * 七牛OSS操作组件
 * Class QiniuOss
 * @package app\components\oss\qiniu
 */
class QiniuOss extends Component{

    public $access_key;
    public $secret_key;
    public $bucket;
    public $bucket_domain;
    public $upload_domain;

    /**
     * @var Auth $auth
     */
    private $auth;

    /**
     * @return Auth
     */
    public function getAuth(){
        if(!$this->auth){
            $this->auth = new Auth($this->access_key,$this->secret_key);
        }
        return $this->auth;
    }

    /**
     * 获取上传凭证
     * @return string
     */
    public function getUploadToken(){
        return $this->getAuth()->uploadToken($this->bucket);
    }

    /**
     * 上传文件
     * @param $key
     * @param $path
     * @return bool
     * @throws \Exception
     */
    public function uploadFile($key,$path){
        $token = $this->getUploadToken();
        // 初始化 UploadManager 对象并进行文件的上传。
        $manager = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $manager->putFile($token, $key, $path);
        return $err == null;
    }
}